//index.js
var userInfo;
const DB = wx.cloud.database()
var util = require('../../utils/util.js')
var id_card_area =require('../../utils/id_card_area.js')
var app =getApp()
let that
// var data{
// 432503199409140615  13977284413
//   phoneNumber: '手机号码',
//   name: '姓名',
//   userNumber: '身份证号码',
//   wxNumber: '微信帐号',
//   shengao: '身高',
//   tizhong: '体重',
//   nssmr: '自我简介',
//   psdah: '兴趣爱好',
//   jyxy: '交友宣言',
//   nxwdt: '你希望的TA是什么样子的？',

//   nicheng 昵称
//   sex: '性别',
//   region1: '籍贯',
//   region2: '所在地区',
//   xuli: '学历',
//   ziyie: '职业',
//   car: '车子',
//   house: '房子',
//   love: '恋爱状态',
//  jtcy 家庭成员
// nianxing1 年薪
// nianxing2 年薪
// zhengmian  身份证正面
// fanmian_img    身份证反面
// }
Page({
  data: {
    page_type: wx.getStorageSync('userInfoDetail') ? false : true,
    list: [{
      text: '手机号码',
      // text_: '仅用于登记，不公开',
      name: 'phoneNumber',
      value: ""
    }, {
      text: '姓名',
      // text_: '仅用于登记，不公开',
      name: 'name',
      value: ""
    }, {
      text: '身份证号',
      // text_: '仅作核实身份之用，不公开',
      name: 'userNumber',
      value: ""
    }, {
      text: '微信帐号',
      text_: '',
      name: 'wxNumber',
      value: ""
    }],
    region1: ['请选择', '请选择', '请选择'],
    region2: ['请选择', '请选择', '请选择'],
    sex: "男",
    customItem: '请选择',
    sex_list: [{
        name: '男',
        checked: 'true',
      },
      {
        name: '女',
      },
    ],
    hande: "",
    arr_list: [],
    live_phone: [],
  },
  
  onLoad: function (option) {
    that = this
    if (option.nav_type == "login") {
      this.setData({
        nav_type: option.nav_type
      })
    }
    try {
      if (wx.getStorageSync('userInfo')) {
        DB.collection('user').doc(wx.getStorageSync('userInfo')._id).get().then(ress => {
          console.log('res', ress.data)
          var list = this.data.list;
          var user =  ress.data.userInfoDetail;
          wx.setStorageSync('userInfo', ress.data)
          console.log(list[0].value, user.phoneNumber)

          if (user.phoneNumber) {
            list[0].value = user.phoneNumber
          }
          if (user.name) list[1].value = user.name
          if (user.userNumber) list[2].value = user.userNumber
          if (user.wxNumber) list[3].value = user.wxNumber

          var sex_list = this.data.sex_list;
          var sex = "男";


          if (user.sex == '男') {
            sex_list[0].checked = true;
            sex_list[1].checked = false;
            sex = "男"
          } else {
            sex = "女"
            sex_list[0].checked = false;
            sex_list[1].checked = true;
          }

          console.log('-----------------', user)
          this.setData({
            list,
            sex_list,
            sex,
            user,...ress.data,
            ...user
          })
        })
      } else {
        console.log('===========')
      }
    } catch (error) {
      console.log('====', error)

    }
  },
  userNumberInput(e){
      //获取出生日期 1  获取性别 2  获取年龄 3
    console.log('userNumberInput---------------',id_card_area.getAreaByIdCard(e.detail.value))
    console.log('获取出生日期',util.IdCard(e.detail.value,1))
    console.log('获取性别',util.IdCard(e.detail.value,2))
    console.log('获取年龄',util.IdCard(e.detail.value,3))

    // 获取出生年月
    var age = util.IdCard(e.detail.value,1);

    // 获取性别
    var sex = util.IdCard(e.detail.value,2);
    var sex_list = this.data.sex_list;
    if(sex=='男'){
      sex_list[0].checked=true
      sex_list[1].checked=false
    }else{
      sex_list[0].checked=false
      sex_list[1].checked=true
    }

    // 获取籍贯
    var region1 = id_card_area.getAreaByIdCard(e.detail.value)
    this.setData({
      sex_list,age,region1,sex
    })
  },
  getPhoneNumber (e) {
    console.log('getPhoneNumber----------------')
    if (!e.detail.errMsg || e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showModal({
        content: '请打开设置授权手机号',
        showCancel: false
      })
      return;
    }
    wx.cloud.callFunction({
      name: 'getToken',  // 对应云函数名
      data: {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        sessionCode: app.sessionCode    // 这个通过wx.login获取，去了解一下就知道。这不多描述
      },
      success: res => {
        wx.hideLoading()
        console.log('成功拿到手机号',res.result.data.phoneNumber)
        this.setData({
          ['list[0].value']:res.result.data.phoneNumber
        })
      },
      fail: err => {
        console.error(err);
        wx.showToast({
          title: '获取手机号失败',
          icon: 'none'
        })
      }
    })
  },
  //日期选择器：
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      age: e.detail.value
    })
  },
  nav_sanguan() {
    if (this.data.nav_type == "login") {
      wx.navigateTo({
        url: '../character_list/index',
      })
    } else {
      wx.navigateTo({
        url: '../character_list/index?lianyuan=user',
      })
    }
  },

  // 废除
  hande_img() {
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        console.log('选择图片', res)
        const tempFilePaths = res.tempFilePaths[0]
        // 将图片上传至云存储空间
        wx.cloud.uploadFile({
          // 指定上传到的云路径
          cloudPath: Date.parse(new Date()) + tempFilePaths[0],
          // 指定要上传的文件的小程序临时文件路径
          filePath: tempFilePaths,
          // 成功回调
          success: res => {
            console.log('上传成功', res)
            // 成功之后的图片地址
            let imgUrl = res.fileID
            that.setData({
              hande: imgUrl
            })
          }
        })
      }
    })
  },
  zhengmian_img() {
    let that = this
    var ctx = wx.createCanvasContext('myCanvas')
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        //获取图片基本信息
        wx.getImageInfo({
          src: res.tempFilePaths[0],
          success: function (res) {
            var width = res.width
            var height = res.height
            //获取屏幕宽度
            let screenWidth = wx.getSystemInfoSync().windowWidth
            //处理一下图片的宽高的比例
            if (width >= height) {
              if (width > screenWidth) {
                width = screenWidth
              }
              height = height / res.width * width
            } else {
              if (width > screenWidth) {
                width = screenWidth
              }
              if (height > 400) {
                height = 400
                width = res.width / res.height * height
              } else {
                height = height / res.width * width
              }
            }
            that.setData({
              imageWidth: width,
              imageHeight: height,
            })
            ctx.drawImage(res.path, 0, 0, width, height)
            ctx.rotate(20 * Math.PI / 180)
            for (let j = 1; j < 12; j++) {
              ctx.beginPath()
              ctx.setFontSize(14)
              ctx.setFillStyle('white')
              ctx.fillText('仅供游友侣行实名认证使用', 0, 50 * j)
              for (let i = 1; i < 12; i++) {
                ctx.beginPath()
                ctx.setFontSize(14)
                ctx.setFillStyle('white')
                ctx.fillText("仅供游友侣行实名认证使用", (15 + (14 - 1) * "仅供游友侣行实名认证使用".length) * i, 50 * j)
              }
            }
            ctx.draw(false, () => {
              //生成图片
              wx.canvasToTempFilePath({
                canvasId: 'myCanvas',
                success: function (res) {
                  console.log("canvas可以生成图片")
                  console.log(res.tempFilePath, 'canvas图片地址');

                  // tempFilePath可以作为img标签的src属性显示图片
                  console.log('选择图片', res)
                  const tempFilePaths = res.tempFilePath
                  wx.cloud.uploadFile({
                    cloudPath: Date.parse(new Date()) + "",
                    filePath: tempFilePaths,
                    success: res => {
                      console.log('上传成功', res)
                      let imgUrl = res.fileID
                      that.setData({
                        zhengmian: imgUrl
                      })
                    },
                    fail: err => {
                      console.log('上传失败', err)
                    }
                  })
                }
              })
            })

          }
        })
      }
    })
  },
  fanmian_img() {
    let that = this
    var ctx = wx.createCanvasContext('myCanvas')
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        //获取图片基本信息
        wx.getImageInfo({
          src: res.tempFilePaths[0],
          success: function (res) {
            var width = res.width
            var height = res.height
            //获取屏幕宽度
            let screenWidth = wx.getSystemInfoSync().windowWidth
            //处理一下图片的宽高的比例
            if (width >= height) {
              if (width > screenWidth) {
                width = screenWidth
              }
              height = height / res.width * width
            } else {
              if (width > screenWidth) {
                width = screenWidth
              }
              if (height > 400) {
                height = 400
                width = res.width / res.height * height
              } else {
                height = height / res.width * width
              }
            }
            that.setData({
              imageWidth: width,
              imageHeight: height,
            })
            ctx.drawImage(res.path, 0, 0, width, height)
            ctx.rotate(20 * Math.PI / 180)
            for (let j = 1; j < 12; j++) {
              ctx.beginPath()
              ctx.setFontSize(14)
              ctx.setFillStyle('white')
              ctx.fillText('仅供游友侣行实名认证使用', 0, 50 * j)
              for (let i = 1; i < 12; i++) {
                ctx.beginPath()
                ctx.setFontSize(14)
                ctx.setFillStyle('white')
                ctx.fillText("仅供游友侣行实名认证使用", (15 + (14 - 1) * "仅供游友侣行实名认证使用".length) * i, 50 * j)
              }
            }
            ctx.draw(false, () => {
              //生成图片
              wx.canvasToTempFilePath({
                canvasId: 'myCanvas',
                success: function (res) {
                  console.log("canvas可以生成图片")
                  console.log(res.tempFilePath, 'canvas图片地址');

                  // tempFilePath可以作为img标签的src属性显示图片
                  console.log('选择图片', res)
                  const tempFilePaths = res.tempFilePath
                  wx.cloud.uploadFile({
                    cloudPath: Date.parse(new Date()) + "",
                    filePath: tempFilePaths,
                    success: res => {
                      console.log('上传成功', res)
                      let imgUrl = res.fileID
                      that.setData({
                        fanmian: imgUrl
                      })
                    },
                    fail: err => {
                      console.log('上传失败', err)
                    }
                  })
                }
              })
            })

          }
        })
      }
    })
  },
  live_phone() {
    let that = this
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        // console.log('选择图片', res)
        const tempFilePaths = res.tempFilePaths
        let i = 0
        for (i; i < tempFilePaths.length; i++) {
          // console.log(i, ':', tempFilePaths[i])
          let url = tempFilePaths[i]
          // 将图片上传至云存储空间
          wx.cloud.uploadFile({
            // 指定上传到的云路径
            cloudPath: Date.parse(new Date()) + i + '.png',
            // 指定要上传的文件的小程序临时文件路径
            filePath: url,
            // 成功回调
            success: res => {
              console.log('上传成功', res)
              // 成功之后的图片地址
              let imgUrl = res.fileID
              let arr = [
                imgUrl
              ]
              console.log('--------', arr, that.data.live_phone)
              var live_phone = that.data.live_phone.concat(arr)
              console.log('--------', live_phone)

              that.setData({
                live_phone
              })

            }
          })
        }

      }
    })
  },
  delete(e) {
    console.log('e', e)
    var idx = e.currentTarget.id;
    var live_phone = this.data.live_phone;
    live_phone.splice(idx, 1);
    this.setData({
      live_phone
    })
  },
  formsubmit: function (e) {
    var that = this;
    var formData = e.detail.value;
    console.log('formData1', formData)
    // if (this.data.hande) formData.hande = this.data.hande;
    if (this.data.live_phone) formData.live_phone = this.data.live_phone;
    if(this.data.live_phone.length<2){
      wx.showToast({
        title: '请上传照片,至少两张',
        icon:'none'
      })
      return
    }
    if(this.data.live_phone.length>9){
      wx.showToast({
        title: '最多上传九张照片',
        icon:'none'
      })
      return
    }
    if (this.data.sex) formData.sex = this.data.sex;
    if (this.data.region1) formData.region1 = this.data.region1[0] == "请选择" ? '' : this.data.region1;
    if (this.data.region2) formData.region2 = this.data.region2[0] == "请选择" ? '' : this.data.region2;
    if (this.data.xuli) formData.xuli = this.data.xuli;
    if (this.data.ziyie) formData.ziyie = this.data.ziyie;
    if (this.data.car) formData.car = this.data.car;
    if (this.data.house) formData.house = this.data.house;
    if (this.data.love) formData.love = this.data.love;
    if (this.data.zhengmian) formData.zhengmian = this.data.zhengmian;
    if (this.data.fanmian) formData.fanmian = this.data.fanmian;
    console.log('formData2', formData)
    this.userAdd(formData)

  },


  userAdd(formData) {
    // if (this.data.user && this.data.user.hande) {
    //   formData.hande = this.data.user.hande
    // }
    console.log(formData.name,  formData.sex, formData.phoneNumber, formData.wxNumber, formData.userNumber)
    if (formData.jyxy.length < 10) {
      wx.showToast({
        title: '交友宣传请输入10字以上',
        icon: 'none'
      })
      return
    }
    if (formData.nssmr.length < 20) {
      wx.showToast({
        title: '自我简介请输入20字以上',
        icon: 'none'
      })
      return
    }
    console.log(!formData.name, !formData.wxNumber, !formData.sex, !formData.phoneNumber, !formData.nicheng, !formData.shengao, !formData.nssmr, !formData.jyxy, !formData.region1, !formData.region2, !formData.love)
    if (!formData.name|| !formData.wxNumber|| !formData.sex|| !formData.phoneNumber|| !formData.nicheng|| !formData.shengao|| !formData.nssmr|| !formData.jyxy|| !formData.region1|| !formData.region2|| !formData.love) {
      wx.showToast({
        title: '请确认信息填写完整',
        icon: 'none'
      })
      return
    }
    if (!util.IdentityCodeValid(formData.userNumber)) {
      wx.showToast({
        title: '身份证信息错误',
        icon: 'none'
      })
      return
    }
    if (!util.regPhone(formData.phoneNumber)) {
      wx.showToast({
        title: '手机号错误',
        icon: 'none'
      })
      return
    }

    wx.setStorageSync('userInfoDetail', formData);
    DB.collection('user').doc(wx.getStorageSync('userInfo')._id).update({
      data: {
        userInfoDetail: formData
      }
    })

    
    if (this.data.nav_type == "login") {
      console.log('11111111111111111111111111')
      wx.navigateTo({
        url: '/pages/character_list/index',
      })
    } else {
      console.log('2222222222222222222222222')

      wx.switchTab({
        url: '/pages/find/index',
      })
    }
  },
  //省市区选择器：
  bindRegionChange1: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region1: e.detail.value
    })
  },
  //省市区选择器：
  bindRegionChange2: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region2: e.detail.value
    })
  },
  next() {
    wx.navigateTo({
      url: '../character_list/index',
      success: function (res) {},
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  input(e) {
    console.log(e)
    let tite = e.currentTarget.dataset.title
    let type = e.currentTarget.dataset.type
    let text = e.detail.value
    let arr = {
      tite: tite,
      type: type,
      text: text
    }
    this.setData({
      arr_list: this.data.arr_list.push(arr)
    })
  },


  radioChange(e) {
    this.setData({
      sex: e.detail.value
    })
  },
  // 学历
  xuli() {
    let list = ['研究生及以上', '本科', '专科及以下']
    wx.showActionSheet({
      itemList: list,
      itemColor: '',
      success: function (res) {
        console.log(res)
        that.setData({
          xuli: list[res.tapIndex]
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  // 职业
  ziyie() {
    let list = ['企业员工', '公务员', '自由职业', '其他']
    wx.showActionSheet({
      itemList: list,
      itemColor: '',
      success: function (res) {
        that.setData({
          ziyie: list[res.tapIndex]
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  //车
  car() {
    let list = ['自己名下全款有车', '自己名下贷款有车', '没车', '家里有车']
    wx.showActionSheet({
      itemList: list,
      itemColor: '',
      success: function (res) {
        that.setData({
          car: list[res.tapIndex]
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  // 房
  house() {
    let list = ['自己名下全款有房', '自己名下贷款有房', '没房', '家里有房']
    wx.showActionSheet({
      itemList: list,
      itemColor: '',
      success: function (res) {
        that.setData({
          house: list[res.tapIndex]
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  // 恋爱状态
  love() {
    let list = ['未恋爱过', '恋爱分手一年内', '恋爱分手多年', '离异自己带子女', '离异无子女', '离异对方带子女']
    wx.showActionSheet({
      itemList: list,
      itemColor: '',
      success: function (res) {
        that.setData({
          love: list[res.tapIndex]
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  onShareAppMessage: function () {
    var res = {
      path: "/pages/user_detail/user_detail?openid=" + wx.getStorageSync('userInfo')._openid + '&share=true',
      success: function (e) {},
      // title: getApp().share_title || null,
      imageUrl:wx.getStorageSync('userInfo').userInfoDetail.hande
    };
    return res;
  },
})